import React, {useEffect, useRef, useState} from 'react';
import makeStyles from "@material-ui/core/styles/makeStyles";
import WebViewer from '@pdftron/webviewer';
import axios from 'axios'
import {BASE_URL, SERVER_ERROR_MESSAGE} from "../constants";
import LoadingSpinner from "../components/LoadingSpinner";
import InlineError from "../components/InlineError";

const useStyle = makeStyles(theme => ({
    root: {
        maxWidth: 1100,
        margin: "auto",
        height: "100vh", // pdf
    },
    errMsg: {
        maxWidth: 1100,
        margin: "auto",
        marginTop: theme.spacing(5)
    }
}))


export default function Book(props) {
    const classes = useStyle()
    const viewer = useRef()
    const title = props.match.params.title

    const [loading, setLoading] = useState(true)
    const [error, setError] = useState('')
    const [pdfPath, setPdfPath] = useState('')

    // WebViewer实例创建两次错误
    // https://pdfjs.community/t/using-instance-loaddocument-inside-useeffect-to-open-a-file/318
    useEffect(() => {
        if (pdfPath) {
            console.log(viewer.current)
            WebViewer(
                {
                    path: '/webviewer/lib',
                    initialDoc: `${pdfPath}`,
                    fullAPI: true,
                },
                viewer.current,
            ).then((instance) => {
                instance.setLanguage('zh_cn')
                //关闭下载功能
                //https://www.pdftron.com/documentation/web/samples/customization/
                //需要注册登录才能下载文件
                instance.disableFeatures([instance.Feature.Download])
                // const {docViewer} = instance;
                // you can now call WebViewer APIs here...
            })
        }

    }, [pdfPath])
    useEffect(() => {
        // 根据书的标题获取书的存放位置
        axios.get(`${BASE_URL}/books/${title}/`)
            .then(response => {
                console.log(response)
                setLoading(false)
                // "/media/it/files/fluent-python.pdf"
                setPdfPath(response.data['pdf_path'])
            })
            .catch(err => {
                setLoading(false)
                setPdfPath('')
                if (err.response && err.response.status === 404) {
                    // 使用后端接口的错误信息
                    setError(err.response.data['detail'])
                }
                else
                    setError(SERVER_ERROR_MESSAGE)
            })
    }, [title]);

    if (loading) return <div className={classes.root}><LoadingSpinner/></div>
    if (error) return <div className={classes.errMsg}><InlineError error={error}/></div>

    return <div className={classes.root} ref={viewer}/>
};

